package net.wangds.jpa.service;

import net.wangds.data.WithId;
import net.wangds.jpa.comp.AbstractMongoComp;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

/**
 * 抽象MongoDB操作服务.
 * <p></p>
 *
 * @author 王东石 2020/5/19 21:49.
 */
public abstract class AbstractMongoService<T extends WithId<String>, C extends AbstractMongoComp<T>> {


    @Transactional
    public void remove(String id) {
        fetchMongoComp().remove(id);
    }

    @Transactional
    public void remove(T target) {
        fetchMongoComp().remove(target);
    }

    @Transactional
    public void erase(T target) {
        fetchMongoComp().erase(target);
    }

    @Transactional
    public T save(T target) {
        return fetchMongoComp().save(target);
    }

    public Optional<T> findById(String id) {
        return fetchMongoComp().findById(id);
    }

    public boolean existsById(String id) {
        return fetchMongoComp().existsById(id);
    }

    public Page<T> findAll(Pageable page) {
        return fetchMongoComp().findAll(page);
    }

    public List<T> findAll(Sort sort) {
        return fetchMongoComp().findAll(sort);
    }

    /**
     * 获得MongoDB JPA组件.
     * @return 组件.
     */
    protected abstract C fetchMongoComp();
}
